<template>
  <div style="width:100vw;display:flex;justify-content: center;background:#F9F9F9">
    <div class="container" style="width:75vw">
      <StuAssignmentNavBar :homeworkId="homeworkId" :semesterId="semesterId" />
      <div style="display:flex;flex-direction:row;background-color: #DCE4F5;">
        <div style="display:flex;align-items: center;margin:20px">
          <button @click="before" class="back-button">
            <img :src="beforeImg" alt="上一个" class="button-image" />
          </button>
        </div>
        
        <div class="assignment-details">
          <!-- 1. 互评未开放 -->
          <template v-if="isNotOpen">
            <img :src="blankImg" style="width:160px;margin:40px auto;display:block">
            <p style="text-align:center;color:#888">互评尚未开放</p>
          </template>

          <!-- 2. 已开放但没人提交 -->
          <template v-else-if="noSubmissions">
            <img :src="blankImg" style="width:160px;margin:40px auto;display:block">
            <p style="text-align:center;color:#888">还没有同学提交作业</p>
          </template>
          <template v-else-if="assignmentData">
          <!-- 学生作业详情 -->
            <!-- 学生头像 -->
            <div style="display: flex; justify-content: center; margin-bottom: 20px;">
              <img :src="studentAvatarUrl" alt="学生头像" style="width: 120px; height: 120px; border-radius: 50%;" />
            </div>
            <div class="detail-container">
              <div class="detail-item">
                <span class="detail-label">学生姓名：</span>
                <span class="detail-value">{{ assignmentData.username }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">提交时间：</span>
                <span class="detail-value">{{ assignmentData.update_time }}</span>
              </div>
              <div class="detail-item vertical">
                <span class="detail-label">作业内容：</span>
                <div class="content" v-html="assignmentData.content"></div>
              </div>
              <div class="detail-item">
                <span class="detail-label">附件：</span>
                <div class="attachment-container">
                  <a v-if="assignmentData.attachment_url" 
                    :href="assignmentData.attachment_url" 
                    target="_blank"
                    class="attachment-link">
                    下载附件
                  </a>
                  <img v-else 
                      src="@/assets/picture/none.png" 
                      class="no-attachment-img" />
                </div>
              </div>
            </div>
          </template>
         </div>
        <!-- 评阅表单 -->
        <div class="grading-form">
          <form @submit.prevent="submitGrade">
            <label for="each_score" style="display: block; margin-right: 10px;">成绩:</label>
            <div class="form-group" style="display:flex;flex-direction:row;align-items: center;margin-bottom: 30px;margin-top: 10px;">
              <input
                type="number"
                v-model.number="formData.each_score"
                :disabled="formData.is_finished"
                id="each_score"
                required
                min="0"
                max="100"
                style="padding: 10px; border: 1px solid #ccc;"
              />
              <p style="margin-left: 10px;">分</p>
            </div>
            <div class="form-group">
              <label for="each_comment" style="display: block; margin-bottom: 15px;">评语:</label>
              <!-- 使用富文本编辑器替换文本域 -->
              <QuillEditor
                v-model="formData.each_comment"
                :readOnly="formData.is_finished" />
            </div>
            <button v-if="!formData.is_finished" type="submit" class="submit-button" style="margin-top: 20px;">提交</button>
          </form>
        </div>

        <!-- 下一个按钮 -->
        <div style="display:flex;align-items: center;margin:20px">
          <button @click="next" class="back-button">
            <img :src="nextImg" alt="下一个" class="button-image" />
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
// import { useRoute, useRouter } from 'vue-router'
import QuillEditor from '@/components/QuillEditor.vue'
import StuAssignmentNavBar from '@/components/StuAssignmentNavBar.vue'
import { ElMessage } from 'element-plus'
import {
  fetchEachReviewList,
  fetchEachReviewDetail,
  submitStudentGrade
} from '@/services/api'

// 静态资源
import beforeImgPath from '@/assets/picture/before.png'
import nextImgPath   from '@/assets/picture/next.png'
import workBlank     from '@/assets/picture/workblank.png'

export default {
  name: 'StuEach',
  components: { StuAssignmentNavBar, QuillEditor },
  props: {
    homeworkId : { type: [String, Number], required: true },
    stuHmwkId  : { type: [String, Number], required: true },
    semesterId : { type: [String, Number], required: true }
  },
  setup (props) {
    /* ———————————————————— 基础 ref ———————————————————— */
    // const route          = useRoute()
    // const router         = useRouter()
    const beforeImg      = beforeImgPath
    const nextImg        = nextImgPath
    const blankImg       = workBlank

    /* ————— 作业状态来自 localStorage ————— */
    // 约定：0/1/2/3  -> 未发布/未开始/进行中/已截止
    const assignmentStatus = ref(Number(localStorage.getItem('hmk_status') || 0))
    console.log('hmk_status', assignmentStatus.value);

    /* ———————————————————— 互评业务数据 ———————————————————— */
    const assignmentList  = ref([])      // 同学列表
    const currentIndex    = ref(0)
    const assignmentData  = ref(null)
    const formData = ref({ each_score: null, each_comment: '', is_finished: false })

    const isNotOpen = computed(() => assignmentStatus.value !== 3)
    const noSubmissions = ref(false)

    /* ————— 头像占位 ————— */
    const defaultAvatar     = require('@/assets/picture/default-avatar.png')
    const studentAvatarUrl  = ref(defaultAvatar)

    /* ———————————————————— 加载互评列表 ———————————————————— */
    const loadEachReviewData = async () => {
      // 1) 互评还没开放
      if (isNotOpen.value) {
        noSubmissions.value = false
        return
      }

      try {
        const userId = localStorage.getItem('id')
        const { data } = await fetchEachReviewList(props.homeworkId, userId)

        if (data.status === 1 && data.data.length) {
          assignmentList.value = data.data
          noSubmissions.value  = false

          // 默认第一条
          selectAssignment(0)
        } else {
          // 已开放但没人提交
          noSubmissions.value = true
        }
      } catch (e) {
        ElMessage.error('获取互评列表失败')
        console.error(e)
      }
    }

    /* ———————————————————— 选中某条作业 ———————————————————— */
    const selectAssignment = async (idx) => {
      const cur = assignmentList.value[idx]
      assignmentData.value = {
        username       : '匿名同学',
        update_time    : cur.create_time,
        content        : cur.content || '该学生没有作答',
        attachment_url : cur.attachment_url,
        img_url        : '',
        stu_hmwk_id    : cur.stu_hmwk_id
      }
      currentIndex.value = idx
      await loadDetail(cur.stu_hmwk_id)
    }

    /* ———————————————————— 详情回显 ———————————————————— */
    const loadDetail = async (stuHmwkId) => {
      const userId = localStorage.getItem('id')
      const { data } = await fetchEachReviewDetail(stuHmwkId, userId)
      if (data.status === 1) {
        formData.value.each_score  = data.data.each_score
        formData.value.each_comment= data.data.each_comment
        formData.value.is_finished = data.data.is_finished
      }
    }

    /* ———————————————————— 上/下一条 ———————————————————— */
    const before = async () => {
      if (currentIndex.value <= 0) return ElMessage.warning('已经是第一个了')
      await selectAssignment(currentIndex.value - 1)
    }
    const next = async () => {
      if (currentIndex.value >= assignmentList.value.length - 1)
        return ElMessage.warning('已经是最后一个了')
      await selectAssignment(currentIndex.value + 1)
    }

    /* ———————————————————— 提交互评 ———————————————————— */
    const submitGrade = async () => {
      try {
        const user_id = localStorage.getItem('id')
        const stu_hmwk_id = assignmentData.value?.stu_hmwk_id
        const payload = {
          user_id,
          identity    : Number(localStorage.getItem('identity') ?? 0),
          each_score  : formData.value.each_score,
          each_comment: formData.value.each_comment
        }
        const { data } = await submitStudentGrade(stu_hmwk_id, payload)
        if (data.status === 1) {
          ElMessage.success('评阅成功！')
          await loadDetail(stu_hmwk_id) // 回显
          next()                        // 自动跳下一个
        } else {
          ElMessage.error(data.msg || '提交失败')
        }
      } catch (e) {
        ElMessage.error('提交失败，请稍后再试')
        console.error(e)
      }
    }

    /* ———————————————————— 生命周期 ———————————————————— */
    onMounted(loadEachReviewData)

    return {
      /* 状态 */
      isNotOpen, noSubmissions, blankImg,
      // 渲染数据
      assignmentData, studentAvatarUrl, formData,
      // 列表操作
      before, next, submitGrade,
      // 资源
      beforeImg, nextImg
    }
  }
}
</script>


<style scoped>
/* 保留您原有的样式 */
.container {
  width: 100vw;
  background: #F9F9F9;
  min-height: 100vh;
  padding: 20px;
  padding-top: 0px;
}
p {
  font-size: 14px;
}

.back-button {
  background-color: #DCE4F5;
  padding: 0;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  margin-bottom: 20px;
  width: 50px;
  height: 90px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-button:hover {
  background-color: #fff;
}

.button-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.assignment-details {
  background-color: #ffffff;
  padding: 60px 30px;
  border-right: 1px solid rgb(237, 237, 237);
  width: 45%;
}

.grading-form {
  background-color: #ffffff;
  padding: 60px 30px;
  width: 30%;
}

.form-group {
  margin-bottom: 15px;
}

.submit-button {
  background-color: #244382;
  color: #fff;
  padding: 10px 40px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  margin-left: 68%;
}

.submit-button:hover {
  background-color: #3e66b0;
}

.detail-container {
  padding: 20px 50px;
}

.detail-item {
  display: grid;
  grid-template-columns: 100px 1fr;
  align-items: start;
  margin-bottom: 18px;
}


.detail-label {
  font-weight: 600;
  color: #2f57a7;
  font-size: 15px;
}

.detail-value {
  color: #4a5568;
  font-size: 14px;
  word-break: break-word;
}

.content {
  width: 100%;
  padding: 8px;
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #e2e8f0;
  border-radius: 4px;
  margin-top: 5px;
}

.attachment-container {
  display: flex;
  align-items: center;
  min-height: 32px;
}

.attachment-link {
  background: #2f57a710;
  color: #2f57a7;
  padding: 6px 12px;
  border-radius: 4px;
  text-decoration: none;
  transition: background 0.2s;
}

.attachment-link:hover {
  background: #2f57a720;
}

.no-attachment-img {
  width: 90px;
  margin-left: 12px;
  opacity: 0.7;
}
</style>
